import React, {useState, useEffect} from 'react';
import {Table, Tag, Space, message} from 'antd';
import OperaModal from '../../components/OperaModal';
import axios from '../../http/axios';
import {addKey} from '../../components/TableAddKey';
import moment from 'moment';
import roomlist from '../../assets/hotelroom.json';

export default function Index() {
  const [table, settable] = useState({
    data: [
      {
        fo_id: '001',
        fo_user: '张飞',
        fo_phone: '151888888',
        fd_id: ['goods', '回过肉', '菠萝饭'],
        fo_address: '1001',
        fo_status: 1,
        pay: '1890',
      },
    ],
    pagination: {
      current: 1,
      pageSize: 10,
    },
    loading: false,
  });
  const [visible, setVisible] = useState({
    openModal: false,
    btnEvent: '',
    editdata: '',
    msg: '',
  });
  const [OptionID, setOptionID] = useState('');
  const columns = [
    {
      title: '用户ID',
      dataIndex: 'fo_user',
      key: 'fo_user',
      render: (name) => `${name}`,
    },
    {
      title: '订餐用户',
      dataIndex: 'fo_user',
      key: 'fo_user',
      render: (name) => `张三`,
    },
    {
      title: '订餐编号',
      dataIndex: 'fo_id',
      key: 'fo_id',
      render: (name) => `${name}`,
    },
    {
      title: '商品详情',
      dataIndex: 'foodOrderItems',
      key: 'foodOrderItems',
      width: '30%',
      render: (record) => goodsList(record),
    },
    {
      title: '下单时间',
      dataIndex: 'fo_time',
      render: (fo_time) => timer(fo_time),
    },
    {
      title: '送餐地址',
      dataIndex: 'room_id',
      render: (room_id) => {
        console.log(roomlist);
        let adress = '';
        roomlist.filter((item) => {
          if (item.id === room_id) {
            return (adress = item.room_address);
          }
        });
        return `${adress}`;
      },
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
      render: (name) => `${name}`,
    },
    {
      title: '订单状态',
      dataIndex: 'fo_status',
      key: 'fo_status',
      render: (name) => setOrderStatus(name),
    },
    {
      title: '订单金额',
      className: 'pay',
      dataIndex: 'pay',
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 300,
      render: (record) => actionif(record),
    },
  ];
  const timer = (t) => {
    let data = t?.split('T') || [];
    return data[0];
  };
  const setOrderStatus = (v) => {
    // console.log('房间状态', v);
    switch (v) {
      case 1:
        return (
          <Tag color="#2db7f5" key={Math.random}>
            已支付
          </Tag>
        );
      case 2:
        return (
          <Tag color="grey" key={Math.random}>
            已退款
          </Tag>
        );
      case 3:
        return (
          <Tag color="geekblue" key={Math.random}>
            订单完成
          </Tag>
        );
      case 4:
        return (
          <Tag color="#f50" key={Math.random}>
            待支付
          </Tag>
        );
      default:
    }
  };

  const actionif = (record) => {
    if (record.fo_status !== 1) {
      return '';
    }
    return (
      <Space size="middle" key={Math.random()}>
        <a
          key={Math.random()}
          onClick={() => {
            setOptionID(record.fo_id);
            opreAction(record, 'songda');
          }}
        >
          送达
        </a>
        <a
          key={Math.random()}
          onClick={() => {
            setOptionID(record.fo_id);
            opreAction(record, 'tuikuan');
          }}
        >
          退款
        </a>
      </Space>
    );
  };

  const goodsList = (record) => {
    // console.log(record);
    if (!record) {
      return;
    }
    return record.map((item, index) => {
      return (
        <div>
          {index + 1}.{item.food_name}
        </div>
      );
    });
  };

  const getTablList = () => {
    axios({
      method: 'GET',
      url: '/foodOrders/queryOrders',
      params: {},
    })
      .then((res) => {
        console.log(res.data);
        const list = addKey(res.data);
        console.log(list);
        settable(() => {
          return {...table, data: list};
        });
      })
      .catch((err) => {});
  };
  const handleTableChange = (pagination, filters, sorter) => {
    fetch({
      sortField: sorter.field,
      sortOrder: sorter.order,
      pagination,
      ...filters,
    });
  };

  const closeModalFn = (e) => {
    console.log(OptionID);
    setVisible(() => {
      return {
        openModal: '',
        btnEvent: '',
        editdata: '',
        msg: '',
      };
    });
    switch (e) {
      case 'songda':
        return axios({
          method: 'POST',
          url: '/foodOrders/hasArrived',
          data: {orderId: OptionID},
        })
          .then((res) => {
            setOptionID('');
            console.log(res.data);
            getTablList();
            message.success('送达成功');
          })
          .catch((err) => {
            setOptionID('');
          });
      case 'tuikuan':
        return axios({
          method: 'POST',
          url: '/foodOrders/backMoney',
          data: {orderId: visible.editdata},
        })
          .then((res) => {
            setOptionID('');
            console.log(res.data);
            getTablList();
            message.success('退款成功');
          })
          .catch((err) => {
            setOptionID('');
          });
      default:
        break;
    }
    return;
  };
  const opreAction = (row, btn) => {
    switch (btn) {
      case 'songda':
        return setVisible(() => {
          return {
            openModal: true,
            btnEvent: btn,
            editdata: row.fo_id,
            msg: '确认已送达?',
          };
        });
      case 'tuikuan':
        return setVisible(() => {
          return {
            openModal: true,
            btnEvent: btn,
            editdata: row.fo_id,
            msg: '确认退款金额' + row.pay + '元?',
          };
        });
      default:
        break;
    }
  };
  useEffect(() => {
    getTablList();
  }, []);
  const {data, pagination, loading} = table;
  return (
    <>
      <Table
        columns={columns}
        rowKey={Math.random()}
        dataSource={data}
        pagination={pagination}
        loading={loading}
        onChange={handleTableChange}
      />
      <OperaModal
        key={Math.random()}
        visible={visible.openModal}
        btnEvent={visible.btnEvent}
        editdata={visible.editdata}
        msg={visible.msg}
        closeModalFn={closeModalFn}
      />
    </>
  );
}
